package com.lkd.handler;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.lkd.business.MsgHandler;
import com.lkd.common.VMSystem;
import com.lkd.config.TopicConfig;
import com.lkd.contract.TaskCompleteContract;
import com.lkd.emq.Topic;
import com.lkd.entity.VendingMachineEntity;
import com.lkd.service.VendingMachineService;
import com.lkd.utils.JsonUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * @author brianxia
 * @version 1.0
 * @date 2023-02-08 14:19
 */
@Component
@Topic(TopicConfig.VMS_COMPLETED_TOPIC)
@Slf4j
public class TaskOperationHandler implements MsgHandler {

    @Autowired
    private VendingMachineService vendingMachineService;

    @Override
    public void process(String jsonMsg) throws IOException {

        if(StringUtils.isBlank(jsonMsg)){
            log.error(TopicConfig.VMS_COMPLETED_TOPIC + "参数为空");
            return;
        }

        //1.售货机编号  2.工单类型
        //工单类型 投放 未运营->运营   撤机 运营 ->撤机
        TaskCompleteContract taskCompleteContract = JsonUtil.getByJson(jsonMsg, TaskCompleteContract.class);

        String innerCode = taskCompleteContract.getInnerCode();

        if(StringUtils.isBlank(innerCode)){
            log.error(TopicConfig.VMS_COMPLETED_TOPIC + "售货机编码为空");
            return;
        }

        int taskType = taskCompleteContract.getTaskType();
        if(taskType == VMSystem.TASK_TYPE_DEPLOY){
            //投放
            //更新到数据库
            vendingMachineService.update(Wrappers.<VendingMachineEntity>lambdaUpdate()
                    .set(VendingMachineEntity::getVmStatus, VMSystem.VM_STATUS_RUNNING)
                    .eq(VendingMachineEntity::getInnerCode, innerCode)
            );
        }else if(taskType == VMSystem.TASK_TYPE_REVOKE){
            //更新到数据库
            vendingMachineService.update(Wrappers.<VendingMachineEntity>lambdaUpdate()
                    .set(VendingMachineEntity::getVmStatus, VMSystem.VM_STATUS_REVOKE)
                    .eq(VendingMachineEntity::getInnerCode, innerCode)
            );
        }

    }
}
